#include <ne.h>
#include <system/GlutApplication.h>

int    Width;               /* Width of window */
int    Height;              /* Height of window */
ne::Engine *pEngine = 0;
ne::GlutApplication *pApplication = 0;
float v = -1;

void keyboard(unsigned char key, int x, int y);
void redraw(void);
void resize(int width, int height);
void init();

int main(int argc, char *argv[]) /* I - Command-line arguments */
{
    pApplication = new ne::GlutApplication();//(argc, argv);
    glutReshapeFunc(resize);
    glutDisplayFunc(redraw);
    glutKeyboardFunc(keyboard);
    //glutFullScreen();

    pEngine = pApplication->engine;
    if (!pEngine || !pEngine->isReady())
    {
        delete pApplication;
        return 0;
    }

    init();

    glutMainLoop();

    delete pApplication;
    
    return 0;
}

void init()
{
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    pEngine->setWorkSpace("../image");
    ne::ImagePtr image = pEngine->getImageManager()->create("BMPLogo", "logo.bmp");
    image->load();
    std::cout << "FreeImage BMP: width=" << image->getWidth() << " height=" << image->getHeight() << " format=" << image->getFormat() << std::endl;

    image = pEngine->getImageManager()->create("PNGLogo", "logo.png");
    image->load();
    std::cout << "FreeImage PNG: width=" << image->getWidth() << " height=" << image->getHeight() << " format=" << image->getFormat() << std::endl;

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}

void keyboard(unsigned char key, int x, int y)
{
    if (key == 'u' || key == 'U')
    {
    }
    else if (key == 'p' || key == 'P')
    {
    }
    else if (key == 0x1b)
    {
        delete pApplication;
        exit(0);
    }
}

void redraw(void)
{
    glShadeModel(GL_SMOOTH);

    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glColor4f(1.0, 0.0, 0.0, 0.75);
    
    glPushMatrix();
        glTranslatef(0, 0, 0);

        v = (v + 0.01);
        if (v >= 1) v = -1;
        glRasterPos2f(v, 0);

        ne::ImagePtr image = pEngine->getImageManager()->getByName("BMPLogo");
        if (image.notNull())
        {
            glRasterPos2f(v, 0.0f);
            glDrawPixels(image->getWidth(), image->getHeight(), image->getFormat(), image->getPixelType(), image->getData());
        }

        image = pEngine->getImageManager()->getByName("PNGLogo");
        if (image.notNull())
        {
            glRasterPos2f(0.0f, v);
            glDrawPixels(image->getWidth(), image->getHeight(), image->getFormat(), image->getPixelType(), image->getData());
        }

    glPopMatrix();
    glutSwapBuffers();
    glutPostRedisplay();
    //Sleep(10);
}

void resize(int width, int height)
{
    /* Save the new width and height */
    Width  = width;
    Height = height;

    /* Reset the viewport... */
    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
}

